<?php

class Admin_QuotesController extends GTL_Action {

    public function init() {
        parent::init();
        /* Initialize action controller here */
        $this->list_sess_unset('controller_quotes');
        $this->session_search_key = 'controller_quotes';
        $this->session_search_name = 'search_label';
    }

    public function indexAction() {
        $this->_helper->redirector('list', 'quotes', 'admin');
    }
	
	public function unsetsessionAction() {
        $pagename = $this->_getParam('pagename');
        unset($_SESSION['_LISTING_SESS']);
        $this->_helper->redirector($pagename, 'quotes', 'admin');
    }

    public function listAction() {

        $errorMessage = Array();
        $successmessage = "";
        $where = "";
        $searchtype = "";
        $orderField = 'quote_id';
        $sort = 'asc';

        if (!isset($_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name])) {
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = "";
        }
        /* Pagination Login */
        $itemsPerPageReviews = $this->PAGING_PER_PAGE;
        $currentPageReviews = 1;
		
        //PAGING_PER_PAGE

        if ($this->_getParam('page') && $this->_getParam('page') != "") {
            $currentPageReviews = $this->_getParam('page');
        }

        if ($this->_getParam('field') && $this->_getParam('field') != "") {
            $orderField = $this->_getParam('field');
        }

        if ($this->_getParam('sort') && $this->_getParam('sort') != "") {
            $sort = $this->_getParam('sort');
        }

        $offset = ($currentPageReviews - 1) * $itemsPerPageReviews;

        if ($this->_request->isPost()) {
            $postedData = $this->_request->getPost();

            //Multiple Delete Logic 
            if (isset($postedData["multiaction"]) && ($postedData["multiaction"] != "")) {
                $action = trim($postedData["multiaction"]);
                if (isset($postedData["multicheck"]) && count($postedData["multicheck"]) > 0) {
                    $ids = implode(",", $_POST["multicheck"]);
                    $result = $this->deleteAction($_POST["multicheck"]);
                } else {
                    $errorMessage[] = "Please select one checkbox";
                }
            }
			/* Search Facility Over Here */
            if (isset($postedData["searchtype"]) && ($postedData["searchtype"] == "")) {
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'] = "";
            }
            if (isset($postedData["searchtype"]) && ($postedData["searchtype"] != "")) {
                $searchtype = $postedData["searchtype"];
                $where = "quote_subject LIKE '%$searchtype%' OR quote_email LIKE '%$searchtype%' OR quote_phone LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'] = $searchtype;
                $this->view->searchtype = $searchtype;
            }
        } else {

            if (!isset($_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'])) {
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'] = '';
            }
			$searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'];
            $where = "quote_subject LIKE '%$searchtype%' OR quote_email LIKE '%$searchtype%' OR quote_phone LIKE '%$searchtype%'";
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'] = $searchtype;
            $this->view->searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'];
        }
		
        //Load Quotes Model
        $quotesModel = new Model_Quotes();
        $quoteData = $quotesModel->fetchQuoteData($where, $itemsPerPageReviews, $offset, $orderField, $sort);
		
        //Paginator logiq
        $paginator = new GTL_Paginator();

        $paginator->setItemsPerPage($itemsPerPageReviews);
        $paginator->setItemsTotal($quotesModel->getQuoteCount($where));
        $paginator->setCurrentPage($currentPageReviews);
        $link = $this->view->url(array('controller' => 'quotes', 'action' => 'list', 'page' => 'PAGENO'), 'default', false);

        $paginator->paginate($link);
		$GTLOBJ = new GTL_Common();

        $this->view->gtlObj = $GTLOBJ;
        $this->view->paginator = $paginator;
        $this->view->quoteData = $quoteData;
        $this->view->errorMessage = $errorMessage;
        $this->view->successmessage = $successmessage;
        $this->view->statusArray = $quotesModel->getStatusArray();
        $this->view->searchtype = $searchtype;
    }

    public function formAction() {
		$uniqueId = uniqid('unq_');
        //Initialize
        $quote_id = '';
        $successmessage = '';
        $errorMessageArray = Array();
        $data = array();
        $quoteData = Array();
		$quote_available_to_everyone = "";
        $this->view->mode = 'Add';
		
		$QuoteFileModel = new Model_Quotesfile();

        //Load Quotes Model
        $quotesModel = new Model_Quotes();
		
		//Load Quotes Form
        $quotesForm = new Form_Admin_Quotes();
		
		//Load client Model
        $clientModel = new Model_Client();
		
		//Load the client array for the select box in form 
        $clientArray = $clientModel->fetchClient();
        $quotesForm->quote_clnt_id->addMultiOptions($clientArray);
		
		//Load company Model
        $companyModel = new Model_Company();
		
		//Load the client array for the select box in form 
        $companyArray = $companyModel->fetchCompany();
        $quotesForm->quote_com_id->addMultiOptions($companyArray);
		
		//Load the Company Industry array for the select box in form 
        $companyindustryArray = $companyModel->getCompanyindustryArray();
		
		//Load the Company Type array for the select box in form 
        $companytypeArray = $companyModel->getCompanytypeArray();
		
		//Load deal Model
        $dealModel = new Model_Deals();
		
		//Load the deal array for the select box in form 
        $dealArray = $dealModel->fetchDeal();
        $quotesForm->quote_deal_id->addMultiOptions($dealArray);

        //Load the status array for the select box in form 
        $statusArray = $quotesModel->getStatusArray();
        $quotesForm->quote_status->addMultiOptions($statusArray);
		
		//Load the quote Currency array for the select box in form 
        $quotecurrencyArray = $quotesModel->getQuotescurrencyArray();
        $quotesForm->quote_currency->addMultiOptions($quotecurrencyArray);
		
		//Load the quote main status array for the select box in form 
        $QuotemainStatusArray = $quotesModel->getQuotesMainStatusArray();
        $quotesForm->quote_main_status->addMultiOptions($QuotemainStatusArray);
		
        //Check for the quote_id Parameter
        $quoteData['quote_id'] = $this->_request->getParam('quote_id');
        $quote_id = (!empty($quoteData['quote_id'])) ? $quoteData['quote_id'] : null;

        if (!empty($quote_id)) {

            //Set the Mode to Edit
            $this->view->mode = 'Edit';
            //Fetch data to be loaded in form 
            $data = $quotesModel->fetchEntryById($quote_id); 
			$QuoteImages = $QuoteFileModel->fetchQuoteFileByQuoteId($quote_id);
			//echo '<pre>';print_r($QuoteImages);exit;
			$quote_available_to_everyone = $data['quote_available_to_everyone'];
			$this->view->QuoteImages = $QuoteImages;
        }

        //Populate form 
        $this->view->form = $quotesForm->populate($data);
		
        if ($this->getRequest()->isPost()) {
			
			//Check for Errors
            $postedData = $this->_request->getPost();
			
			if ($postedData['UNIQUEIDENTIFIER'] != '') {
                $uniqueId = $postedData['UNIQUEIDENTIFIER'];
            }
			
            if (!$quotesForm->isValid($postedData)) {
                $errorMessage = $quotesForm->getMessages();
                foreach ($errorMessage as $_err) {
                    foreach ($_err as $_val) {
                        $errorMessageArray[] = $_val;
                    }
                }
            } else {
               
                if (count($errorMessageArray) > 0) {
                    
                } else {

					if ($this->view->mode == 'Add') {
                        $quoteData['quote_createddate'] = date('Y-m-d H:i:s');
						$quoteData['quote_addedby'] = $this->USER->lgn_id;
                    }
                    //Deal save
                    $quoteData['quote_id'] = $quote_id;
                    $quoteData['quote_subject'] = $postedData['quote_subject'];
                    $quoteData['quote_main_status'] = $postedData['quote_main_status'];
					$quoteData['quote_currency'] = $postedData['quote_currency'];
					$quoteData['quote_amount'] = $postedData['quote_amount'];
					$quoteData['quote_responsible'] = $this->USER->lgn_id;
					$quoteData['quote_startdate'] = date('Y-m-d H:i:s');
					$quoteData['quote_enddate'] = date('Y-m-d H:i:s');
                    $quoteData['quote_deal_id'] = $postedData['quote_deal_id'];
					if (array_key_exists('quote_available_to_everyone', $postedData)) {
						$quoteData['quote_available_to_everyone'] = $postedData['quote_available_to_everyone'];
					} else {
						$quoteData['quote_available_to_everyone'] = 0;
					}
					$quoteData['quote_clnt_id'] = $postedData['quote_clnt_id'];
					$quoteData['quote_com_id'] = $postedData['quote_com_id'];
					$quoteData['quote_client'] = $postedData['quote_client'];
					$quoteData['quote_adrline1'] = $postedData['quote_adrline1'];
					$quoteData['quote_adrline2'] = $postedData['quote_adrline2'];
					$quoteData['quote_adrline3'] = $postedData['quote_adrline3'];
					$quoteData['quote_street'] = $postedData['quote_street'];
					$quoteData['quote_postal'] = $postedData['quote_postal'];
					$quoteData['quote_city'] = $postedData['quote_city'];
					$quoteData['quote_country'] = $postedData['quote_country'];
					$quoteData['quote_email'] = $postedData['quote_email'];
					$quoteData['quote_phone'] = $postedData['quote_phone'];
					$quoteData['quote_content'] = $postedData['quote_content'];
					$quoteData['quote_condition'] = $postedData['quote_condition'];
					$quoteData['quote_status'] = $postedData['quote_status'];
					$quoteData['quote_updatedby'] = $this->USER->lgn_id;
                    $quoteData['quote_updateddate'] = date('Y-m-d H:i:s');
					
                    $quote_id = $quotesModel->save($quoteData, 'quote_id');
					//echo '<pre>';print_r($quoteData);exit;
					$QuoteFileModel->update(Array('qf_quote_id' => $quote_id), "qf_identifier = '" . $uniqueId . "'");
                    if ($this->view->mode == 'Add') {
                        $successmessage = 'Quotes add successfully';
                    } else {
                        $successmessage = 'Quotes updated successfully';
                    }
                    $this->addSuccessMessage($successmessage);
                    $this->_helper->redirector('list', 'quotes', 'admin');
                }
            }
        }
        $this->view->quoteid = $quote_id;
		$this->view->UNIQUEIDENTIFIER = $uniqueId;
		$this->view->companyindustryArray = $companyindustryArray;
		$this->view->companytypeArray = $companytypeArray;
		$this->view->quote_available_to_everyone = $quote_available_to_everyone;
		$this->view->errorMessageArray = $errorMessageArray;
        $this->view->succesMessage = $successmessage;
        $this->view->form = $quotesForm;
    }
	
	public function deletedropzonefileAction() {
      
        if ($this->_getParam('fid') && $this->_getParam('fid') != "") {

            $imageid = $this->_getParam('fid');
            $QuoteFileModel = new Model_Quotesfile();
            $quotefile = $QuoteFileModel->fetchQuotefile("qf_id = '" . $imageid . "'");
            foreach ($quotefile as $_img) {
                $folder = $this->config->UPLOAD_PATH . "quotesfile/";
                $imgPath = $folder . $_img['qf_filename'];
                if (file_exists($imgPath)) {
                    unlink($imgPath);
                }
                $QuoteFileModel->delete("qf_id = '" . $imageid . "'");
            }
        }

        exit;
    }
	
	public function uploadAction() {
			
        error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
        $upload = new Zend_File_Transfer_Adapter_Http();

        foreach ($upload->getFileInfo() as $fields => $asFileInfo) {

            if ($asFileInfo['name'] != '') {
				 $folder = $this->config->UPLOAD_PATH . "quotesfile/";
                if ($this->getRequest()->isPost()) {
                    $postedData = $this->_request->getPost();
                    if ($postedData['UNIQUEIDENTIFIER'] != '') {
                        $upload->setDestination($folder);
                        $originalFilename = pathinfo($asFileInfo['name']);
                        $file_name = preg_replace("/[^-_a-zA-Z0-9]+/i", "_", $originalFilename['filename']) . '_' . time() . '.' . $originalFilename['extension'];
                        $upload->addFilter('Rename', $file_name, 'filename');
                        $upload->receive($fields);
                            $QuoteFileModel = new Model_Quotesfile();
                            $qfData = Array();
                            $qfData['qf_quote_id'] = '';
                            $qfData['qf_filename'] = $file_name;
                            $qfData['qf_uploadedname'] = $originalFilename['basename'];
							$qfData['qf_identifier'] = $postedData['UNIQUEIDENTIFIER'];
                            $qfData['qf_createddate'] = date('Y-m-d H:i:s');
							$qfData['qf_updateddate'] = date('Y-m-d H:i:s');
							$qfData['qf_addedby'] = $this->USER->lgn_id;
							$qfData['qf_updatedby'] = $this->USER->lgn_id;
							$qfData['qf_status'] = 1;
                            $imageid = $QuoteFileModel->save($qfData, 'memd_id');
                            echo $this->view->ADMIN_URL . "quotes/deletedropzonefile/fid/" . $imageid;
                    }
                }
            }
        }

        exit;
    }
	
	public function addcompanyAction() {
		 
		$comp_id = "";
		 
		//Load company Model
        $companyModel = new Model_Company();

        if ($this->getRequest()->isPost()) {
            $postdata = $this->_request->getPost();
            $companyData = array();
                    $companyData['comp_id'] = $comp_id;
					$companyData['comp_name'] = $postdata['comp_name'];
                    $companyData['comp_type'] = $postdata['comp_type'];
                    $companyData['comp_industry'] = $postdata['comp_industry'];
                    $companyData['comp_email'] = $postdata['comp_email'];
					$companyData['comp_phone'] = $postdata['comp_phone'];
					$companyData['comp_adrline1'] = $postdata['comp_adrline1'];
					$companyData['comp_addedby'] = $this->USER->lgn_id;
					$companyData['comp_updatedby'] = $this->USER->lgn_id;
					$companyData['comp_responsible_person'] = $this->USER->lgn_id;
					$companyData['comp_createddate'] = date('Y-m-d H:i:s');
                    $companyData['comp_updateddate'] = date('Y-m-d H:i:s');
                    $companyData['comp_status'] = 1;
					$company_last_id = $companyModel->save($companyData, 'comp_id');
              
            echo $company_last_id;
        }
        exit;
		 
	}
	
	public function getcompanylistAction() {
		
        // $areaString = "<option>-- Select Area--</option>";
        if ($this->getRequest()->isPost()) {
            $postedData = $this->_request->getPost();
			
			$companyModel = new Model_Company();
			$CompanyArray = $companyModel->fetchCompany();
			
			if (count($CompanyArray) > 0) {
				$companyString = "";
				$selected = "";
				foreach ($CompanyArray as $comp_id => $comp_name) {
					
					if ($postedData['company_last_id'] == $comp_id){
						$selected = "selected";
					}
					
					$companyString .= "<option " . $selected . " value='" . $comp_id . "'>" . $comp_name . "</option>";
				}
			}        
        }
        echo $companyString;
        exit;
    }
	 
	public function addclientAction() {
		 
		$clnt_id = "";
		 
		//Load client Model
        $clientModel = new Model_Client();

        if ($this->getRequest()->isPost()) {
            $postdata = $this->_request->getPost();
            $clientData = array();
                    $clientData['clnt_id'] = $clnt_id;
					$clientData['clnt_first_name'] = $postdata['clnt_first_name'];
                    $clientData['clnt_middle_name'] = $postdata['clnt_middle_name'];
                    $clientData['clnt_last_name'] = $postdata['clnt_last_name'];
                    $clientData['clnt_email'] = $postdata['clnt_email'];
					$clientData['clnt_phone'] = $postdata['clnt_phone'];
					$clientData['clnt_addedby'] = $this->USER->lgn_id;
					$clientData['clnt_updatedby'] = $this->USER->lgn_id;
					$clientData['clnt_responsible'] = $this->USER->lgn_id;
					$clientData['clnt_createddate'] = date('Y-m-d H:i:s');
                    $clientData['clnt_updateddate'] = date('Y-m-d H:i:s');
                    $clientData['clnt_status'] = 1;
					$client_last_id = $clientModel->save($clientData, 'clnt_id');
              
            echo $client_last_id;
        }
        exit;
		 
	}
	 
	 
	public function getclientlistAction() {
		
        // $areaString = "<option>-- Select Area--</option>";
        if ($this->getRequest()->isPost()) {
            $postedData = $this->_request->getPost();
			
			//Load client Model
			$clientModel = new Model_Client();
			$ClientArray = $clientModel->fetchClient();
			
			if (count($ClientArray) > 0) {
				$clientString = "";
				$selected = "";
				foreach ($ClientArray as $clnt_id => $client_name) {
					
					if ($postedData['client_last_id'] == $clnt_id){
						$selected = "selected";
					}
					
					$clientString .= "<option " . $selected . " value='" . $clnt_id . "'>" . $client_name . "</option>";
				}
			}        
        }
        echo $clientString;
        exit;
    }


    public function deleteAction($ids = Array()) {
		
		//Load quote Model
        $quotesModel = new Model_Quotes();
		
        if ($this->_getParam('quote_id') && $this->_getParam('quote_id') != '') {
            $quote_id = $this->_getParam('quote_id');

            $quoteData = array();
            $quoteData = $quotesModel->fetchEntryById($quote_id);
            
            $quotesModel->deleteQuote($quote_id);
            $this->addSuccessMessage('Quotes Successfully Deleted');
            $this->_helper->redirector('list', 'quotes', 'admin');
        } else {
            $quotesModel->deleteQuote($ids);
            $this->addSuccessMessage('Quotes Successfully Deleted');
            $this->_helper->redirector('list', 'quotes', 'admin');
        }
    }
}
?>